package com.littlerpc.protocol.net.netty.codec;

import com.littlerpc.protocol.codec.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 *
 * @author ChengPeng
 * @date 2017/6/14
 * 编码器
 */
public class NettyEncoder extends MessageToByteEncoder<Object>{

    private Serializer serializer;
    private Class<?> genericClass;


    public NettyEncoder(Serializer serializer, Class<?> genericClass) {
        this.serializer = serializer;
        this.genericClass = genericClass;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {

        if (genericClass.isInstance(msg)) {
            byte[] serialize = serializer.serialize(msg);
            //防止读半包
            out.writeInt(serialize.length);
            out.writeBytes(serialize);
        }

    }
}
